package com.bubblegumproject.ogo.component.injection;

import com.bubblegumproject.ogo.component.JavaBeanProperty;
import org.apache.log4j.Logger;

/**
 * @author Azubuko Obele (buko.obele@gmail.com)
 */
public class Injector {

    private Object component;

    private JavaBeanProperty property;

    private Inject metadata;

    private boolean satisfied;

    private boolean manuallySet;

    private static final Logger log = Logger.getLogger(Injector.class);

    public Injector(Object component, JavaBeanProperty property, Inject metadata) {
        this.component = component;
        this.property = property;
        this.metadata = metadata;
    }

    public boolean isSatisfied() {
        return (!manuallySet && satisfied) || metadata.optional();
    }

    public void inject(Object dependency) {
        if (!satisfied && property.hasGetter() && property.get(component) != null) {
            log.debug(this + " will not inject value " + dependency + " because it has already been manually set.");
            manuallySet = true;
            return;
        }
        
        if (!satisfied) {
            property.set(component, dependency);
            satisfied = true;
        } else {
            log.info(this + " is conflicted; ignoring new value " + dependency);
        }
    }

    public Class getTargetType() {
        return property.getPropertyType();
    }

    public Inject getMetadata() {
        return metadata;
    }

    public boolean isNamed() {
        return metadata.name().length() > 0;
    }

    public String getName() {
        return metadata.name();
    }

    public String toString() {
        return "[" + getClass().getSimpleName() + " component=" + component + " property=" + property +
                " satisfied=" + satisfied + "]";
    }
}